import json
import numpy as np
from sentence_transformers import SentenceTransformer

embedding_model = SentenceTransformer(
    "Qwen/Qwen3-Embedding-0.6B",
    cache_folder="/Users/wangziqi/.cache/huggingface/hub"
)

def cal_content_embedding(content):
    embedding = embedding_model.encode([content])[0]
    return embedding

def pass_test_case(test_case):
    no_ues_signal = ['HU_WiperRainSensitivitySet', 'RLS_Wiper_speed', 'BCM_WiperRainSensitivity', 'BCM_Rain_sensitivity', 'PCU_PwrTrainSts']
    
    tests = test_case.get('basic_tests', []) + test_case.get('extend_tests', [])
    for test in tests:
        for signal in no_ues_signal:
            if signal in test.get('preconditions', '') or signal in test.get('operate_step', ''):
                return True
    return False
        


def find_most_similar_requirement(target_requirement, all_test_cases):
    target_embedding = cal_content_embedding(target_requirement)
    
    most_similar_requirement = None
    highest_similarity = -1
    
    for single_test_case in all_test_cases:
        if pass_test_case(single_test_case):
            continue
        if target_requirement == single_test_case["requirement"]:
            continue
        sim = np.dot(target_embedding, np.array(single_test_case["requirement_embedding"])) / (
            np.linalg.norm(target_embedding) * np.linalg.norm(np.array(single_test_case["requirement_embedding"]))
        )
        
        if sim > highest_similarity:
            highest_similarity = sim
            most_similar_requirement = single_test_case

    return most_similar_requirement

direct_use_case_id = [
    'G393_BDC-2568'
    "G393_BDC-2582",
    "G393_BDC-2587",
    "G393_BDC-2595",
    "G393_BDC-8381",
    "G393_BDC-2607",
    "G393_BDC-2615",
    "G393_BDC-2619",
    "G393_BDC-16396",
    "G393_BDC-16399",
    "G393_BDC-2625",
    "G393_BDC-2629",
    "G393_BDC-2630"
]
def find_most_similar_test(target_test_case, target_case_id, all_test_cases):
    target_embedding = cal_content_embedding(target_test_case)
    
    highest_similarity = -1
    most_similar_test_case = None

    for single_test_case in all_test_cases:
        if pass_test_case(single_test_case):
            continue
        if target_case_id == single_test_case["case_id"]:
            if target_case_id in direct_use_case_id:
                return single_test_case
            continue
        if not single_test_case.get('extend_tests'):
            continue
        for single_emb in single_test_case['basic_test_embeddings']:
            sim = np.dot(target_embedding, single_emb) / (
                np.linalg.norm(target_embedding) * np.linalg.norm(single_emb)
            )
            if sim > highest_similarity:
                highest_similarity = sim
                most_similar_test_case = single_test_case
    
    return most_similar_test_case


def check_presence(target_embedding, compare_embeddings, similarity_score):
    for emb in compare_embeddings:
        # cosine similarity
        sim = np.dot(target_embedding, emb) / (
            np.linalg.norm(target_embedding) * np.linalg.norm(emb)
        )

        if sim > similarity_score:
            return True
    return False


def get_tests_embeddings(all_test_cases):
    all_test_content_embeddings = []
    for single_generated_basic_test in all_test_cases:
        # 对冒烟测试用例进行编码，防止生成的扩展测试用例和冒烟相同
        test_content = json.dumps(
            {
                "preconditions": single_generated_basic_test.get(
                    "preconditions", ""
                ),
                "operate_step": single_generated_basic_test.get("operate_step", ""),
                "expected_results": single_generated_basic_test.get(
                    "expected_results", ""
                ),
            },
            ensure_ascii=False,
            indent=2,
        )
        all_test_content_embeddings.append(cal_content_embedding(test_content))
    return all_test_content_embeddings